package OOPAndMultiThreadArchiveManager.Client.Views;

import OOPAndMultiThreadArchiveManager.Client.Controllers.HttpController;
import OOPAndMultiThreadArchiveManager.Client.Models.ApiReceive;
import OOPAndMultiThreadArchiveManager.Client.Models.ApiResponse;
import OOPAndMultiThreadArchiveManager.Client.Models.UserInfo;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.swing.*;
import java.util.concurrent.CompletableFuture;

public class LoginView {
    private JTextField usernameField;
    private JPanel MainForm;
    private JPasswordField passwordField;
    private JButton Login;
    private ObjectMapper objectMapper = new ObjectMapper();
    private JFrame frame;
    private ApiReceive loginRequest = new ApiReceive();

    public LoginView() {
        Login.addActionListener(e -> loginAsync());
        loginRequest.api = ApiReceive.Api.POST_Login;

        frame = new JFrame("LoginView");
        frame.setContentPane(MainForm);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();

        frame.setSize(600, 360);
        frame.setLocationRelativeTo(MainForm);
        frame.setVisible(true);
    }

    private void loginAsync() {
        loginRequest.user.name = usernameField.getText();
        loginRequest.user.password = String.valueOf(passwordField.getPassword());
        if (!loginRequest.user.isValid()) {
            JOptionPane.showMessageDialog(frame, "验证失败，请检查你的账号和密码。");
            return;
        }
        CompletableFuture.supplyAsync(() -> new HttpController().Request(loginRequest))
                .whenCompleteAsync(((response, throwable) -> {
                    if (response.apiCode == ApiResponse.ApiCode.Success) {
                        var role = objectMapper.convertValue(response.data, String.class);
                        var userInfo = new UserInfo(loginRequest.user.name, loginRequest.user.password, role);
                        frame.dispose();
                        new MainView(userInfo);
                    } else if (response.apiCode == ApiResponse.ApiCode.Unauthorized) {
                        JOptionPane.showMessageDialog(frame, "验证失败，请检查你的账号和密码。");
                    } else if (response.apiCode == ApiResponse.ApiCode.Failed) {
                        JOptionPane.showMessageDialog(frame, objectMapper.convertValue(response.data, String.class));
                    }
                }));
    }
}
